package com.lucky.common.util;

import cn.idev.excel.ExcelWriter;
import cn.idev.excel.FastExcel;
import cn.idev.excel.write.metadata.WriteSheet;
import cn.idev.excel.write.metadata.fill.FillConfig;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.*;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

/**
 * The Class ExcelExportHandle.
 * 
 * @author  zhangchao
 * Excel 导出操作类
 */
public class ExcelUtil {


	public static <T> byte[] toExcel(Class<T> clazz, List<T> dataList, String sheetName) throws IOException {
		try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
			FastExcel.write(out, clazz).sheet(sheetName).doWrite(dataList);
			return out.toByteArray();
		}
	}

	public static ResponseEntity<byte[]> download(byte[] data, String filename) throws IOException {
		// 输出PDF到响应输出流
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDisposition(ContentDisposition.attachment().filename(filename).build());

		return ResponseEntity.ok().headers(headers).body(data);
	}


	public static String toFile(byte[] data, String filePath) throws IOException {
		try(FileOutputStream fos = new FileOutputStream(filePath)) {
			fos.write(data);
		}
		// 4. 构建 ResponseEntity 并返回
		return filePath;
	}

	public static <T> byte[] toExcel(List<T> dataList, Map<String, String> dataMap, InputStream template, String sheetname) throws IOException {
		//获取模板静态资源
		try (ByteArrayOutputStream out = new ByteArrayOutputStream();
			 ExcelWriter excelWriter = FastExcel.write(out).withTemplate(template).build()) {
			//获取模板的sheet1页
			WriteSheet sheet1 = FastExcel.writerSheet(sheetname).build();
			//填充模板第一部分的列表数据
			FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
			excelWriter.fill(dataList, fillConfig, sheet1);
			//填充列表下面的字段
			excelWriter.fill(dataMap, sheet1);


			//sheet2页也可以
			/**    */
//			//获取导出数据源列表
			excelWriter.finish();
			return out.toByteArray();
		}
	}



}